package com.task.aspect;

import com.alibaba.fastjson.JSON;
import com.task.common.annotation.Log;
import com.task.common.enums.BusinessType;
import com.task.common.util.thread.TaskAsync;
import com.task.common.entity.sys.OperatorLog;
import com.task.common.util.ip.AddressUtils;
import com.task.common.util.ip.IpUtils;
import com.task.common.util.security.SecurityUtils;
import com.task.common.util.servlet.ServletUtils;
import com.task.common.util.string.StringUtils;
import com.task.async.LogTask;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collection;
import java.util.Date;
import java.util.Map;

/**
 * @author Huzz
 * @created 2021-12-08 10:25
 */
@Aspect
@Component
public class LogAspect {

    private static final Logger logger = LoggerFactory.getLogger(LogAspect.class);

    /**
     * 处理完逻辑后切入
     *
     * @param joinPoint  Aspect切点
     * @param log        绑定Aspect的切入点表达式
     * @param returnData Aspect签名中将返回值绑定到的参数名称
     */
    @AfterReturning(pointcut = "@annotation(log)", returning = "returnData")
    public void doAfterRunning(JoinPoint joinPoint, Log log, Object returnData) {
        handleLog(joinPoint, log, null, returnData);
    }

    protected void handleLog(final JoinPoint joinPoint, Log log, final Exception e, Object returnData) {
        try {
            OperatorLog operatorLog = new OperatorLog();
            operatorLog.setStatus(0);
            operatorLog.setRequestIp(IpUtils.getIpAddr(ServletUtils.getRequest()));
            operatorLog.setRequestLocation(AddressUtils.getRealAddressByIP(operatorLog.getRequestIp()));
            operatorLog.setRequestUrl(ServletUtils.getRequest().getRequestURI());
            operatorLog.setOperatorTime(new Date());
            if (StringUtils.isNotNull(e)) {
                operatorLog.setStatus(1);
                operatorLog.setErrorMessage(StringUtils.substring(e.getMessage(), 0, 2000));
            }
            // 设置方法名称
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            operatorLog.setMethod(className + "." + methodName + "()");
            operatorLog.setRequestMethod(ServletUtils.getRequest().getMethod());
            // 处理设置注解上的参数
            getControllerMethodDescription(joinPoint, log, operatorLog, returnData);

            // 执行任务: 保存操作日志
            TaskAsync.executeTask(LogTask.insertOperatorLogTask(operatorLog));
        } catch (Exception exp) {
            // 记录本地异常日志
            logger.error("⚠通知异常: 操作日志异常");
            logger.error("异常信息:{}", exp.getMessage());
            exp.printStackTrace();
        }
    }

    /**
     * 获取注解中对方法的描述信息 用于Controller层注解
     *
     * @param log     日志
     * @param operatorLog 操作日志
     * @throws Exception
     */
    public void getControllerMethodDescription(JoinPoint joinPoint, Log log, OperatorLog operatorLog, Object returnData) throws Exception {

        operatorLog.setBusinessType(log.businessType().getValue());
        operatorLog.setTitle(log.title());
        operatorLog.setOperatorType(log.OperatorType().getCode());
        /**
         * 登录用户不能获取到用户信息
         */
        if (!log.businessType().getValue().equals(BusinessType.LOGIN.getValue())) {
            operatorLog.setOperatorUserId(SecurityUtils.getUserId());
            operatorLog.setOperatorUserUsername(SecurityUtils.getUsername());
        }

        // 是否需要保存request，参数和值
        if (log.isSaveRequestParam()) {
            // 获取参数的信息，传入到数据库中。
            setRequestValue(joinPoint, operatorLog);
        }
        // 是否需要保存response，参数和值
        if (log.isSaveResponseParam() && StringUtils.isNotNull(returnData)) {
            operatorLog.setResponseParam(JSON.toJSONString(returnData));
        }
    }

    /**
     * 获取请求的参数，放到log中
     *
     * @param operatorLog 操作日志
     * @throws Exception 异常
     */
    private void setRequestValue(JoinPoint joinPoint, OperatorLog operatorLog) throws Exception {
        String requestMethod = operatorLog.getRequestMethod();
        if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
            String params = argsArrayToString(joinPoint.getArgs());
            operatorLog.setRequestParam(params);
        } else {
            Map<?, ?> paramsMap = (Map<?, ?>) ServletUtils.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
            operatorLog.setRequestParam(paramsMap.toString());
        }
    }

    /**
     * 参数拼装
     */
    private String argsArrayToString(Object[] paramsArray) {
        String params = "";
        if (paramsArray != null && paramsArray.length > 0) {
            for (Object o : paramsArray) {
                if (StringUtils.isNotNull(o) && !isFilterObject(o)) {
                    try {
                        Object jsonObj = JSON.toJSON(o);
                        params += jsonObj.toString() + " ";
                    } catch (Exception e) {
                    }
                }
            }
        }
        return params.trim();
    }

    /**
     * 判断是否需要过滤的对象。
     *
     * @param o 对象信息。
     * @return 如果是需要过滤的对象，则返回true；否则返回false。
     */
    @SuppressWarnings("rawtypes")
    public boolean isFilterObject(final Object o) {
        Class<?> clazz = o.getClass();
        if (clazz.isArray()) {
            return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
        } else if (Collection.class.isAssignableFrom(clazz)) {
            Collection collection = (Collection) o;
            for (Object value : collection) {
                return value instanceof MultipartFile;
            }
        } else if (Map.class.isAssignableFrom(clazz)) {
            Map map = (Map) o;
            for (Object value : map.entrySet()) {
                Map.Entry entry = (Map.Entry) value;
                return entry.getValue() instanceof MultipartFile;
            }
        }
        return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse
                || o instanceof BindingResult;
    }

}
